package com.qf.security;

import cn.hutool.json.JSONUtil;
import com.qf.entity.SysUser;
import com.qf.utils.security.JwtUtils;
import com.qf.utils.security.RsaUtils;
import com.qf.vo.Result;
import io.jsonwebtoken.JwtException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.List;

/**
 * <p>title: com.qf.security</p>
 * <p>Company: wendao</p>
 * author zhuximing
 * date 2021/9/23
 * description: 自定义认证
 * 获取令牌
 * 解析令牌
 * 将用户信息放入springsecurity的context中
 *
 * 该过滤器拦截所有的请求(/**)
 */

public class FengmiBasicAuthenticationFilter extends BasicAuthenticationFilter {
    public FengmiBasicAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {


        //放行登录请求
        String requestURI = request.getRequestURI();
        if("/user/login".equals(requestURI)){
            //放行
            chain.doFilter(request,response);

            return;
        }

        if("/user/verify".equals(requestURI)){
            //放行
            chain.doFilter(request,response);

            return;
        }


        //从请求头中获取jwt令牌
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)){

            //直接拦截，并给客户端响应
            response(response,new Result<>(false,"令牌不能为空"));

            return;
        }


        try {
            //校验令牌
            PublicKey publicKey = RsaUtils.getPublicKey(ResourceUtils.getFile("classpath:rsa_pub").getPath());

            SysUser infoFromToken = (SysUser) JwtUtils.getInfoFromToken(token, publicKey, SysUser.class);


            //封装用户的角色和权限
            String roles = infoFromToken.getRoles();
            String permission = infoFromToken.getPermission();  //ROLE_ADMIN,ROLE_PRODUCT,a,b,c,d
            List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(roles + permission);

            //将用户的信息放入springsecurity的context中

            UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(infoFromToken, null,
                    authorities/*用户的角色和权限信息*/);

            SecurityContextHolder.getContext().setAuthentication(authenticationToken);


            //放行
            chain.doFilter(request,response);

        } catch (Exception exception) {
            exception.printStackTrace();
            if(exception instanceof JwtException){
                response(response,new Result<>(false,"令牌不合法"));
            }else{
                response(response,new Result<>(false,"其他异常"));
            }

        }


    }

    private void  response(HttpServletResponse response, Result res){
        try {
            response.setContentType("application/json;charset=utf-8");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            PrintWriter out = response.getWriter();

            out.write(JSONUtil.toJsonPrettyStr(res));
            out.flush();
            out.close();
        }catch (Exception e){

        }

    }
}